package com.secondshop.session;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;

import com.secondshop.mappers.GoodMapper;
import com.secondshop.models.Cart;
import com.secondshop.models.Good;
import com.secondshop.services.CollectService;
import com.secondshop.services.GoodService;
import com.secondshop.services.ImageService;
import com.secondshop.services.ReviewService;
import com.secondshop.services.TypeService;
import com.secondshop.services.UserService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Servlet implementation class AddCart
 */
@Controller
@WebServlet("/session/addCart")
public class AddCart extends HttpServlet {
	private final GoodService goodService;
	private final TypeService typeService;
	private final ReviewService reviewService;
	private final UserService userService;
	private final ImageService imageService;
	private final CollectService collectService;
	
	@Autowired
	public AddCart(GoodService goodService, TypeService typeService,
			ReviewService reviewService, UserService userService,
			ImageService imageService, CollectService collectService) {
		this.goodService = goodService;
		this.typeService = typeService;
		this.reviewService = reviewService;
		this.userService = userService;
		this.imageService = imageService;
		this.collectService = collectService;
	}
	

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	
	 int id =Integer.parseInt(request.getParameter("id"));
	//根据goodId查找商品
		if(id!=0){
			Good g = goodService.getGoodById(id);
			
			//从session获取购物车对象
			HttpSession session=request.getSession();
			Cart cart=(Cart) session.getAttribute("cart");
			//首次说明session中没有购物车
			if(cart==null) {
				 cart =new Cart();
			}
			//把商品添加到购物车
			cart.addCart(g);
			//重定向到购物页面
			response.sendRedirect(request.getContextPath()+"/homeGoods.jsp");
			return;
			
		}


	}
}
